package com.manor.paradise.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.manor.common.dialog.XCodeImgPopup
import com.mob.adsdk.AdSdk
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.manor.common.http.JCommonHttpUtil
import com.manor.common.http.JHttpCallback
import com.manor.common.ktx.toBean
import com.manor.common.utils.ClickUtil
import com.manor.common.utils.ToastUtil
import com.manor.common.utils.*
import com.manor.paradise.R
import com.manor.paradise.adapter.HoneyAdapter
import com.manor.paradise.bean.AssetsBean
import com.manor.paradise.bean.DoIsTaskBean
import com.manor.paradise.bean.HoneyBean
import com.manor.paradise.bean.TaskVideoBean
import com.manor.paradise.dialog.CompletePopup
import com.manor.paradise.http.ElvesHttpConst
import com.manor.paradise.http.ElvesHttpUtil
import kotlinx.android.synthetic.main.fragment_get_honey.*
import java.math.BigDecimal

/**
 * 获取蜜糖
 */
class GetHoneyFragment : Fragment(), View.OnClickListener {

    var mCurView: View? = null
    internal var pageNum = 1
    internal lateinit var mAdapter: HoneyAdapter
    internal var im_list: ArrayList<ImageView> = ArrayList()
    private val recordList = mutableListOf<HoneyBean.RecordsBean>()

    private val handler: Handler? = Handler(Looper.getMainLooper())

    companion object {
        fun newInstance(): GetHoneyFragment {
            return GetHoneyFragment()
        }
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        mCurView = inflater.inflate(R.layout.fragment_get_honey, container, false)
        return mCurView
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        ARouter.getInstance().inject(this)
        rcv_list.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        mAdapter = HoneyAdapter(R.layout.item_honey_list, recordList)
        rcv_list?.adapter = mAdapter

        im_list.add(im_honey1)
        im_list.add(im_honey2)
        im_list.add(im_honey3)
        im_list.add(im_honey4)
        im_list.add(im_honey5)
        im_honey1.setOnClickListener(this)
        im_honey2.setOnClickListener(this)
        im_honey3.setOnClickListener(this)
        im_honey4.setOnClickListener(this)
        im_honey5.setOnClickListener(this)
        tv_senior_honey.setOnClickListener(this)

        KLog.e("tag", "////////////// onViewCreated is not null ${mCurView != null}")
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                pageNum++
                setData()
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageNum = 1
                setData()
            }
        })
        nsv_view.scrollTo(0, 0)
        nsv_view.smoothScrollTo(0, 0)
    }


    fun setInfoData() {
        ElvesHttpUtil.getAssetsValue(object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                if (isDetached)
                    return
                var assetsBean: AssetsBean = GsonUtil.gsonToBean<AssetsBean>(info, AssetsBean::class.java)
                KLog.e("json", assetsBean)
                tv_cz?.text = "当日产量  " + assetsBean.todayCrystalOre.toString()
                tv_ks?.text = "我有米粒  " + assetsBean.crystalOre.toString()

                tv_gaoji?.text = "获取高级饲料（" + assetsBean.todaySeniorHoney.toString() + "/1）"
                if (assetsBean.todaySeniorHoney == 1) {
                    tv_senior_honey?.isEnabled = false
                }
                //  var a =  BigDecimal("5").multiply(BigDecimal("100"))

                if (assetsBean.isBseniorHoney) {
                    tv_context?.text = "获取饲料（" + assetsBean.todayHoney.toString() + "/5）"
                    ll_gj?.visibility = View.VISIBLE
                    tv_gaoji?.visibility = View.VISIBLE
                    tv_senior_honey?.visibility = View.VISIBLE
                    var num = (assetsBean.todayHoney + assetsBean.todaySeniorHoney).toBigDecimal()
                    var b = num.divide(BigDecimal("6"), 2, BigDecimal.ROUND_DOWN).multiply(BigDecimal("100")).intValueExact()
                    pbv?.setmProgress(b)
                } else {
                    tv_context?.text = "获取饲料（" + assetsBean.todayHoney.toString() + "/5）"
                    ll_gj?.visibility = View.GONE
                    tv_gaoji?.visibility = View.GONE
                    tv_senior_honey?.visibility = View.GONE
                    var b = BigDecimal(assetsBean.todayHoney.toString()).divide(BigDecimal("5"), 2, BigDecimal.ROUND_DOWN).multiply(BigDecimal("100")).intValueExact()
                    pbv?.setmProgress(b)
                }

                if (assetsBean.todaySeniorHoney.toString() == "1") {
                    tv_senior_honey?.isEnabled = false
                    tv_senior_honey?.setImageResource(R.mipmap.pic_senior_honey_s)
                }
                for (imageView in im_list.indices) {
                    if (imageView < assetsBean.todayHoney) {
                        im_list[imageView]?.isEnabled = false
                        im_list[imageView]?.setImageResource(R.mipmap.pic_honey_ing)
                    }
                }
            }

        })
    }

    override fun onResume() {
        super.onResume()
        userVisibleHint = true
        setInfoData()
        KLog.e("GetHoneyZ", "onResume-------------------")
    }

    override fun onDestroyView() {
        handler?.removeCallbacks(null)
        super.onDestroyView()
    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        KLog.e("GetHoneyZ", "setUserVisibleHint ${isVisibleToUser}-------------------")

        if (ClickUtil.canClick(1000))
            if (isVisibleToUser) {
                pageNum = 1
                setData()
                setInfoData()
            }
    }

    override fun onClick(v: View?) {
        if (ClickUtil.canClick(1000))
            when (v?.id) {
                R.id.tv_senior_honey -> {
                    //getOldAd()
                    doAdvert()
                }
                R.id.im_honey1 -> {
                    //getOldAd()
                    doAdvert()
                }
                R.id.im_honey2 -> {
                    //getOldAd()
                    doAdvert()
                }
                R.id.im_honey3 -> {
                    //getOldAd()
                    doAdvert()
                }
                R.id.im_honey4 -> {
                    //getOldAd()
                    doAdvert()
                }
                R.id.im_honey5 -> {
                    //getOldAd()
                    doAdvert()
                }


            }
    }


    /**
     * 查看视频激励广告
     */
    private fun doAdvert() {
        activity?.let {
            var advReward = false
            AdSdk.getInstance().loadRewardVideoAd(it, "rv1", false,
                    object : AdSdk.RewardVideoAdListener {
                        override fun onAdLoad(id: String?) {
                        }

                        override fun onVideoCached(id: String?) {
                        }

                        override fun onReward(id: String?) {
                            advReward = true

                        }

                        override fun onAdShow(id: String?) {
                        }

                        override fun onAdClick(id: String?) {
                        }

                        override fun onVideoComplete(id: String?) {
                        }

                        override fun onAdClose(id: String?) {
                            if (advReward) {
                                advReward = false
                                getReward()
                            }
                        }

                        override fun onError(id: String?, p1: Int, p2: String?) {
                        }

                    })
        }

    }

    private fun getReward() {
        JCommonHttpUtil.doTaskIsFinish("2", object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String?, info: String?) {
                val bean = info?.toBean<DoIsTaskBean>()
                if (bean?.bfinished == "false" && bean?.bopenDoTask == "true") {

                    if (bean?.bneedVerification == "true") {

                        val timeCount = bean.timeRemaining?.toIntOrNull() ?: 60
                        val vCode = bean.verifyCode ?: ""
                        val timeStamp =  bean.timeStamp ?: ""
                        activity?.let {
                            XCodeImgPopup.load(it, vCode, timeStamp, "2", timeCount) {
                                ix ->
                                CompletePopup.load(it){
                                    handler?.postDelayed({ setInfoData() }, 1000)
                                    setInfoData()
                                }
                            }

//                            XVerifyPopup.load(it, object : SimpleCallback() {}) { boo, t ->
//                                if (boo) {
//                                    riskToken = t
//                                    doTask(bean?.verifyCode ?: "", bean?.timeStamp ?: "")
//                                }
//                            }
                        }
                    } else {
                        doTask(bean?.verifyCode ?: "", bean?.timeStamp ?: "", "", "")
                    }

                } else {
                    msg?.let { ToastUtil.show(it) }
                }
            }
        })
    }

    private fun doTask(code: String, timeStamp: String, random: String, imgCode: String) {
        JCommonHttpUtil.getAdTask("", code, timeStamp, random, imgCode, "2", object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 1509) {
                }

                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }

                activity?.let {
                    CompletePopup.load(it){
                        handler?.postDelayed({
                            setInfoData()
                        }, 1000)
                        setInfoData()
                    }
                }

            }
        })
    }



    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        KLog.e("tag", "////////////// onCreate is not null ${mCurView != null}")
    }


    fun setData() {
        ElvesHttpUtil.getTaskList(pageNum, object : JHttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code != 200) {
                    ToastUtil.show(msg)
                    return
                }
                if (StringUtil.isEmpty(info)) {
                    ///ToastUtil.show("服务器返回错误")
                    return
                }
                var shopListBean: HoneyBean = GsonUtil.gsonToBean<HoneyBean>(info, HoneyBean::class.java)
                KLog.e("json", shopListBean)
                if (pageNum == 1) {
                    recordList.clear()
                    recordList.addAll(shopListBean.records)
                    refreshLayout?.finishRefresh()
                } else {
                    recordList.addAll(shopListBean.records)
                    refreshLayout?.finishLoadMore()
                }
                mAdapter?.notifyDataSetChanged()

            }

        })
    }

    override fun onDestroy() {

        ElvesHttpUtil.cancel(ElvesHttpConst.POST_OPEN_PAGE_VALUE)
        ElvesHttpUtil.cancel(ElvesHttpConst.POST_OPEN_USER_ANIMA_LIST)
        super.onDestroy()
    }

}